import { useUserStore } from '@/store/modules/user'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'

export const routes: RouteRecordRaw[] = []

const modules = import.meta.glob<any>('./modules/*.ts', { eager: true })
for (const path in modules) {
  if (Array.isArray(modules[path].default)) {
    modules[path].default.map((v: any) => routes.push(v))
  } else {
    routes.push(modules[path].default)
  }
}

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
  strict: false,
})

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  document.title = (to.meta.title as string ?? '') + ' - PUMS'


  if (userStore.token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      next()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login`)
    }
  }
})

router.afterEach(() => { })

export default router
